<?php

namespace plugin\admin\app\controller;

use app\traits\DataProcessor;
use app\traits\StatusProcess;
use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use support\Request;
use support\Response;
use plugin\admin\app\model\WorshipSurnameHall;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 先祖宗祠 
 */
class WorshipSurnameHallController extends Crud
{
    
    /**
     * @var WorshipSurnameHall
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new WorshipSurnameHall;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('worship-surname-hall/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('worship-surname-hall/insert');
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        DataProcessor::processSwitch($data, 'is_enable');

        if ($data['is_enable'] == 0) {
            $data['reject_time'] = date('Y-m-d H:i:s');
        }

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('worship-surname-hall/update', [
            'detail' => WorshipSurnameHall::find($request->get('id'))
        ]);
    }

    protected function formatNormal($items, $total): Response
    {
        foreach ($items as $key=>$item) {
            $items[$key]['status_text'] = StatusProcess::process($item);
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

}
